﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PageTitle" runat="server">
    <title>月度考勤管理</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageStyles" runat="server">
    <link href="../../Content/table_jui.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/Attendance/attendance.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .tableContainer
        {
            word-break: break-all;
            word-wrap: break-word;
        }
        .attendanceInfod
        {
            width: 80px;
        }
        .expText
        {
            margin-left: 10px;
            width: 50px;
        }
        .applicationTarget
        {
            color: #008B00;
        }
    </style>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageScripts" runat="server">
    <script src="../../Scripts/jquery.dataTables.js" type="text/javascript"></script>
    <script type="text/javascript">
    //************* URL常量

    
    //************* 全局变量

    var g_Var = {
        'startYear': null,
        'currentUserId': null,
        'targetTime': null,
        'isHasPermisson': null

    };

    //************* 常量定义
    var StaticResource = {
        "WeekendInfo": {
            "false": "非周末",
            "true": "周末"
        },
        "IsNeedToWork": {
            "false": "休息",
            "true": "正常上班"
        },
        "AttendanceType": {
            "onDuty": "上班: ",
            "offDuty": "下班: "
        },
        "AttendanceEvaluation": {
            "Late": "迟到: ",
            "LeaveEarly": "早退: ",
            "Absense": "[旷工]",
            "ExtraWork": "[加班]",
            "ManHours": "获得工时: "
        },

        "timeTarget": {
            "minute": "分钟",
            "hour": "小时"
        },


        "leaveInfo": {
            "leaveForWorkOrNot": {
                "true": "[工作假期]",
                "false": "[个人假期]"
            },

            "leaveTime": "时间: ",
            "leaveType": "类别: "
        }
    };
    var memberSelector = null;

    var AttdendacneTypeResource = {
        'onDuty': StaticResource.AttendanceType.onDuty,
        'offDuty': StaticResource.AttendanceType.offDuty
    };


    var convertor = {
        "星期": function (item) {
            var attendanceTime = Date.fromEpoch(item.theDayInfo.Date);
            var attendanceDate = attendanceTime.toFullDate();
            var day = attendanceTime.getDay();
            var attendanceDay = "星期" + "日一二三四五六".charAt(day);
            
            return attendanceDay 
        },
        "日期": function (item) {
            var attendanceTime = Date.fromEpoch(item.theDayInfo.Date);
            var attendanceDate = attendanceTime.toFullDate();
           
            return attendanceDate;
        },
         "考勤记录": function (item) {
            //打卡所有记录
            var attendanceDetail;
            var attendanceList = item.AttendanceInfoList;
            for (var key in attendanceList) {
                //上班
                if (attendanceList[key].AttendanceType == "onDuty") {
                    attendanceDetail += AttdendacneTypeResource.onDuty
                        + Date.fromEpoch(attendanceList[key].ActionTime).toFullTimeFormat() 
                        + "<br\>";
                }
                // 下班：
                else {
                    attendanceDetail += AttdendacneTypeResource.offDuty
                        + Date.fromEpoch(attendanceList[key].ActionTime).toFullTimeFormat()
                        + "<br\>";
                }
            }
           return attendanceDetail?attendanceDetail:' -- ';
        },

        "假期": function (item) {
            var leaveInfo = " -- ";
            var brTarget = "<br\>"

            if (item.LeaveInfo) {
                var leaveList = item.LeaveInfo.Leaves;
                for (var key in leaveList) {
                    var isForWork = leaveList[key].IsForWork;
                    var startTime = Date.fromEpoch(leaveList[key].StartTime);
                    var endTime = Date.fromEpoch(leaveList[key].EndTime);
                    var startTimeFormat = startTime.toFullTimeFormat();
                    var endTimeFormat = endTime.toFullTimeFormat();

                    var leaveTime = startTimeFormat + " 至 " + endTimeFormat;

                    leaveInfo = StaticResource.leaveInfo.leaveType
                       + leaveList[key].LeaveTypeName
                       + StaticResource.leaveInfo.leaveForWorkOrNot[isForWork]
                       + brTarget
                       + StaticResource.leaveInfo.leaveTime
                       + leaveTime
                       + brTarget
                       + brTarget;
                }
            }

            return leaveInfo;
        },

        "考勤评估": function (item) {
            var evaluationStr = item.EvaluationStr;
            var applicationStr = item.Application;
            var modifyStr = item.ModifyHistoryStr;
            if(applicationStr.length != 0)
                evaluationStr = evaluationStr + "</br>" + applicationStr;
            if(modifyStr.length != 0)
                evaluationStr = evaluationStr + "</br>" + modifyStr;
            return evaluationStr;
        },

        "备注": function (item) {
            var remarkStr = " -- ";
            if(item.RemarkInfo){
                remarkStr =  item.RemarkInfo.Remark; 
            }
            return remarkStr;
        },
       
        "状态": function (item) {
            return  item.EvaluationClassName;
        }
         

    };



    //************* Accessor访问器

    var EzAccessor = {};
    if (ezmock.IS_MOCKED) {
      
    } else {
        var realEzAccessor = {
            'getCurrentUser': function () {
                return <%= ViewData["CurrentUser"] %>;
            },

            'getDeptList': function () {
                 return <%= ViewData["CurrentDeptList"] %>;
            },
            'getIsHasPermisson': function () {
                return <%= ViewData["IsHasPermisson"] %>;
            },
            'getCurrentTime': function () {
                return <%= ViewData["CurrentTime"] %>;
            },
            'getBasicInfo': function () {
                g_Var['startYear'] = <%= ViewData["StartYear"] %>;
                g_Var['targetTime'] = Date.fromEpoch(<%= ViewData["TargetTime"] %>);
            }
        };
        EzAccessor = realEzAccessor;
    }



    ///bindMonthList
    function bindMonthList() {
        EzAccessor.getBasicInfo();

        var currentMonth = g_Var.targetTime.getMonth() + 1;
        var monthDownList = getMonthList();
        ///部门下拉菜单
        $("#cmbMonthList")
              .comboxBinding(monthDownList, 'text', 'value')
              .val(currentMonth)
              .change(function () {
                  updateTitleInfo();

                  ///更新假期数据
                  updateAttendanceList();
              }
        );

    }

    ///bindYearList
    function bindYearList() {
        EzAccessor.getBasicInfo();

        var currentYear = g_Var.targetTime.getFullYear();
        var yearDownList = getYearList();
        ///部门下拉菜单
        $("#cmbYearList")
        .comboxBinding(yearDownList, 'text', 'value')
        .val(currentYear)
        .change(function () {
            updateTitleInfo();

            ///更新假期数据
            updateAttendanceList();
        });
    }

    ///get yearList
    function getYearList() {
        var yearList = [];
        EzAccessor.getBasicInfo();
        var currentYear = g_Var['targetTime'].getFullYear();

        for (var i = g_Var['startYear']; i <= currentYear; i++) {
            yearList.push({ "text": i,
                "value": i
            });
        }
        return yearList;
    }

    ///get monthList
    function getMonthList() {
        var monthList = [];
        for (var i = 1; i <= 12; i++) {
            monthList.push({ "text": i,
                "value": i
            });
        }
        return monthList;
    }




    ///updateTitleInfo
    function updateTitleInfo() {
        var currentMember = $('#memberSelector').memberSelector("getMember");

        var title = currentMember.Name + "考勤信息";
        var dateTitle = $("#cmbYearList").find("option:selected").text()
                        + "年"
                        + " "
                        + $("#cmbMonthList").find("option:selected").text()
                        + "月";


        $('#cmbTitleInfo').html(title);
        $('#cmbDateTitleInfo').html(dateTitle);
    }


    function isFutureDate(year, month) {
        var isFuture = false;
        var time = Date.fromEpoch(EzAccessor.getCurrentTime());
        var targetTimeToEpoch = new Date(
                time.getFullYear(),
                time.getMonth() + 1,
                0,
                0,
                0,
                0

            ).toEpoch();

        var dateToEpoch = new Date(
                year,
                month,
                0,
                0,
                0,
                0
            ).toEpoch();

        if (targetTimeToEpoch < dateToEpoch) {
            isFuture = true;
        }

        return isFuture;
    }


    ///updateAttendanceList
    function updateAttendanceList() {
        var month = $('#cmbMonthList').val();
        var year = $('#cmbYearList').val();

        var isFuture = isFutureDate(year, month);

        if (!isFuture) {
            $('#tblNoFuture').hide();
            $('#divAttendanceListPerMonth').show();
            $.AjaxBusy.show();
            EzDesk.Service.PersonalAttendanceListPerMonth_Cache(function (e) {
                        showPersonalAttendanceStatistics(e);
                        bindAttendanceList(e.MonthAttendanceInfoList);
                        $.AjaxBusy.hide();
                    },{ 'currentMonth': month, 'currentYear': year, "userId": g_Var['currentUserId'] });
        }
        else {
            $('#tblNoFuture').show();
            bindAttendanceList();
            $('#divAttendanceListPerMonth').hide();
        }
    }


    function showPersonalAttendanceStatistics(personalMonthAttendanceJson)
    {
        var statisticsData = {};
        statisticsData.User = EzDesk.Service.GetCurrentUser_CacheSync();
        
        statisticsData.OvertimeDayCount     = personalMonthAttendanceJson.OvertimeDayCount;
        statisticsData.LateDayCount         = personalMonthAttendanceJson.LateDayCount;
        statisticsData.ExtraManhoursInMonth = personalMonthAttendanceJson.ExtraManhoursInMonth;
        statisticsData.ExtraFoodInMonth     = personalMonthAttendanceJson.ExtraFoodInMonth;
        statisticsData.AbsenseDayCount      = personalMonthAttendanceJson.AbsenseDayCount;
        statisticsData.LeaveDayCount        = personalMonthAttendanceJson.LeaveDayCount;
        statisticsData.WorkDayCount         = personalMonthAttendanceJson.WorkDayCount;

        $('#personal-attendance-statistics').html($('#personalAttendanceStatistics').tmpl(statisticsData));
    }

    ///bindAttendanceList
    function bindAttendanceList(personalAttendanceJson) {
        var data = DataConverterForDataTable.convertData(personalAttendanceJson, convertor);
        data.bPaginate = false;
        data.bRetrieve = true;
        data.bFilter = false;
        data.bSort = false;
        data.bInfo = false;

        data.fnRowCallback = function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            $($('td', nRow)[6]).remove()
            var calssName = aData[6];

           
            $(nRow).removeClass('odd');
            $(nRow).removeClass('even');
            $(nRow).addClass(calssName);
            
            return nRow;
        };
        
        data.fnHeaderCallback = function (nHead, aasData, iStart, iEnd, aiDisplay) {
            // 隐藏第6列
            $($('th', nHead)[6]).remove();
        }

        $('#divAttendanceListPerMonth').empty();
        var tblAttendanceListPerMonth = $('<table id="tblAttendanceListPerMonth" class="tbl"/>')
            .appendTo('#divAttendanceListPerMonth')
        var oTable = $('#tblAttendanceListPerMonth')
            .dataTable(data);
       
        setTableCulumn();
        if(personalAttendanceJson){
            setEventColumn();            
        }
        
    }

    function setTableCulumn() {
        var dayColumnHead = $('#tblAttendanceListPerMonth thead tr th')[0];
        $(dayColumnHead).css({
            'width': '52px'
        });
        var dateColumnHead = $('#tblAttendanceListPerMonth thead tr th')[1];
        $(dateColumnHead).css({
            'width': '84px'
        });

        var acctionColumnHead = $('#tblAttendanceListPerMonth thead tr th')[2];
        $(acctionColumnHead).css({
            'width': '102px'
        })

        var leaveColumnHead = $('#tblAttendanceListPerMonth thead tr th')[3];
        $(leaveColumnHead).css({
            'width': '78px'
        });

        var evaluationColumnHead = $('#tblAttendanceListPerMonth thead tr th')[4];
        $(evaluationColumnHead).css({
            'width': '108px'
        });
        
    }


    //事件
    function setEventColumn() {
        var setTRCss = function (tr, color , mouseStatus){
            $(tr).css({
                "background-color": color,
                "cursor" : mouseStatus,
            });    
        };

        $('#tblAttendanceListPerMonth tbody tr').each( function () {
            var backgroundColor = $(this).css('background-color');
                $(this).hover(function() {
                    var _self = $(this);
                    setTRCss(_self, '#eee', 'pointer');
                 }, function() {
                    var _self = $(this);
                    setTRCss(_self, backgroundColor, 'default');
            })
           
            
        });

        $('#tblAttendanceListPerMonth tbody tr').each( function () {
            $(this).click(function() {
                var _self = $(this);

                var isHasPermisson = EzAccessor.getIsHasPermisson();
                var timeDom = $(this).find('td')[1];
                var timeStr = $(timeDom).html();
                var time = timeStr.toDateTime().toEpoch(); 

                if(isHasPermisson){
                    //HR
                   var targetUserId = $('#memberSelector').memberSelector("getMember").Id;
                    window.location.href = '/Attendance/ModifyAttendanceInfoPerDay?time=' + time + '&userId=' + targetUserId;
                }
            });
        });
    }


    //处理下拉菜单是否可操作
    function setSelectorAttr(bool) {
        //下拉菜单dissable
        $('#cmbMonthList').attr("disabled", bool);
        $('#cmbYearList').attr("disabled", bool);
        $('.cmbMemberList').attr("disabled", bool);
        $('.cmbDepartmentList').attr("disabled", bool);
    }




    function initPage() {
        $('#tip_Choose').eztips();
               
        EzTipsManager.showTipBox('tipRemind');
      
        bindMonthList();
        bindYearList();

        var currentUser = EzAccessor.getCurrentUser();
        var deptList = EzAccessor.getDeptList();
        g_Var.isHasPermisson = EzAccessor.getIsHasPermisson();

        $('#memberSelector').memberSelector({
            deptList: deptList,
            currentUser: currentUser,
            memberChanged: function (event, id) {
                g_Var['currentUserId'] = id;

                //下拉菜单dissable
                setSelectorAttr(true);
                //缓冲数据加载
                bindAttendanceList(null);
                ///更新标题
                updateTitleInfo();
                ///更新假期数据
                updateAttendanceList();

                //下拉菜单enabele
                setSelectorAttr(false);

            }

        });

        if (g_Var.isHasPermisson) {
            EzTipsManager.showTipBox('tipChoose');

        }

    }

    function initPageEvent() {

    }
    $(function () {

        initPage();
        initPageEvent();
    });
    </script>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageHead" runat="server">
    <%
        Html.RenderPartial("_sayHello"); %>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageContent" runat="server">
    <div id="page-head" class="page-head">
        <div>
            <img src="../../Content/icons/attendance_perMonth.png" style="width: 48px; height: 48px;"
                alt="perMonth" />
            <span id="cmbTitleInfo" class="title"></span>
            <div style="display: inline-block;">
                <select id="cmbYearList">
                </select>
                <span>年</span>
                <select id="cmbMonthList">
                </select>
                <span>月</span>
            </div>
        </div>
    </div>
    <div id="page-body">
        <span id="cmbDateTitleInfo" style="font-weight: bold;"></span>
        <hr />
        <div id="tblNoFuture" style="display: none;">
            <%Html.RenderPartial("_noFutureDisplayInfo"); %>
        </div>
        <div id="personal-attendance-statistics">
        </div>
        <div id="divAttendanceListPerMonth">
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="PageShortcut" runat="server">
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="PageFoot" runat="server">
    <div id="tip_Choose" style="display: none;">
        <h1>
            选择员工:</h1>
        <p id="memberSelector" class="indent">
        </p>
    </div>
    <div id="tip_Remind" style="display: none;">
        <h1>
            小贴士:</h1>
        <p class="indent">
        </p>
    </div>
</asp:Content>
